package com.sakura.二叉树;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;

public class Code101_对称二叉树 {


    // Definition for a binary tree node.
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    // 迭代
    public boolean isSymmetric_1(TreeNode root) {
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offerFirst(root.left);
        queue.offerLast(root.right);
        while (!queue.isEmpty()) {
            TreeNode leftNode = queue.pollFirst();
            TreeNode rightNode = queue.pollLast();
            if (leftNode == null && rightNode == null) {
                continue;
            }
            if (leftNode == null || rightNode == null || leftNode.val != rightNode.val) {
                return false;
            }
            // 1 2
            // 左边 与右边
            queue.offerFirst(leftNode.left);
            queue.offerFirst(leftNode.right);
            // 2 1
            // 右 左
            queue.offerLast(rightNode.right);
            queue.offerLast(rightNode.left);
            // 1 2 2 1
        }
        return true;
    }

    // 递归
    public boolean isSymmetric(TreeNode root) {
        return compere(root.left, root.right);
    }

    private boolean compere(TreeNode left, TreeNode right) {
        if (left != null && right == null) return false;
        else if (left == null && right != null) return false;
        else if (left == null && right == null) return true;
        else if (left.val != right.val) return false;

        boolean outside = compere(left.left, right.right);// 左
        boolean inside = compere(left.right, right.left); // 右
        return outside && inside; // 中
    }
}
